package com.adams.action.businessviewcount;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.adams.access.db.bean.ActionType;
import com.adams.access.db.bean.DicColumn;
import com.adams.action.view.ViewAction;
import com.adams.core.exception.BusinessException;
import com.adams.custom.page.core.BusinessDealFlowContext;
import com.adams.custom.page.core.dto.DicColumnDto;
import com.adams.custom.page.core.service.BusinessDealFlowEngineService;
import com.adams.custom.page.util.ViewUtil;
import com.adams.encache.mechanism.CacheUtil;
import com.adams.utils.DateUtil;

public class BusinessViewCountAction extends ViewAction {

    private static final long serialVersionUID = 1L;
    private static final String IS_COUNT_YES="1";
    private static final String IS_COUNT_NO="0";
    private static final String T_BUSSINESS_CODE="t_bussiness_code";
    private static final String T_BUSINESS_PAGECOUNT="t_business_pagecount";
    BusinessDealFlowEngineService businessDealFlowEngineService;

    public BusinessDealFlowEngineService getBusinessDealFlowEngineService() {
        return businessDealFlowEngineService;
    }

    public void setBusinessDealFlowEngineService(BusinessDealFlowEngineService businessDealFlowEngineService) {
        this.businessDealFlowEngineService = businessDealFlowEngineService;
    }

    /**
     * 导出Excel
     * 
     * @return
     * @throws Exception
     */
    public String getExcelDataByCount() throws Exception {
        String date_before_acreatetime = request.getParameter("date_before_acreatetime");
        String date_after_acreatetime = request.getParameter("date_after_acreatetime");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = "";
        String nowDate = dateFormat.format(new Date());
        if (null != date_before_acreatetime && !"".equals(date_before_acreatetime) && null != date_after_acreatetime
                && !"".equals(date_after_acreatetime)) {
            fileName = date_before_acreatetime + "至" + date_after_acreatetime;
        } else if (null != date_before_acreatetime && !"".equals(date_before_acreatetime)) {
            fileName = date_before_acreatetime + "至" + nowDate;
        } else if (null != date_after_acreatetime && !"".equals(date_after_acreatetime)) {
            fileName = "至" + date_after_acreatetime;
        }
        if (!"".equals(fileName)) {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls" + "\"");
        }
     //   Map inputMap = ViewAction.requestParameterMap2Map(request);
        List countList = getCountBusinessList();
        super.getExcelData(countList);
        return null;
    }

    /**
     * 按业务统计浏览量
     * 
     * @return
     * @throws Exception
     */
    public String getViewCount() throws Exception {
        List<Map> countList = getCountBusinessList();

        Map map = viewParseService.getParseGridDatasFromList(getUserId(), gridPanelId, countList, countList.size());
        write(JSONObject.fromObject(map).toString());

        return null;
    }

    private List<Map> getCountBusinessList() throws Exception {
        if (ViewUtil.isNuLLStr(gridPanelId)) {
            gridPanelId = request.getParameter("gridPanelId");
        }
        if (ViewUtil.isNuLLStr(searchPanelId)) {
            searchPanelId = request.getParameter("searchPanelId");
        }
        Map inputMap = ViewAction.requestParameterMap2Map(request);

        // 业务名称
        String bname = (String) inputMap.get("businessname");
        
        // 开始时间
        String startTimeStr = (String) inputMap.get("date_before_bcreatetime");
        // 结束时间
        String endTimeStr = (String) inputMap.get("date_after_bcreatetime");

        String start = (String) inputMap.get("start");
        String limit = (String) inputMap.get("limit");

        StringBuffer sql = new StringBuffer(
                "select code.businessname,count(*) from t_business_pagecount tbus join t_bussiness_code  code  on code.id=tbus.businessname where 1=1 and  code.iscount=1");
        if (!"".equals(bname) && bname != null) {
            bname=URLDecoder.decode(bname,"UTF-8");
            sql.append("  and  code.businessname like '%" + bname + "%'   ");
        }

        // -1 < ,0 = ,1>

        if (startTimeStr != null && !startTimeStr.equals("") && endTimeStr != null && !endTimeStr.equals("")) {
            if (startTimeStr.compareTo(endTimeStr) > 0) {
                throw new Exception("开始时间不能大于结束时间");
            }

            if (endTimeStr.compareTo(startTimeStr) < 0) {
                throw new Exception("结束时间不能小于开始时间");
            }

        }

        if (startTimeStr != null && !startTimeStr.equals("")) {
            sql.append("  and createtime>='" + startTimeStr + "' ");
        }

        if (endTimeStr != null && !endTimeStr.equals("")) {
            endTimeStr = endTimeStr + " 23:59:59";
            sql.append("  and createtime<='" + endTimeStr + "' ");
        }

        sql.append(" group by code.businessname");

        // 查询虚拟表字段
        List<DicColumn> dicColumns = dicTableService.findDBDicColumnsByTablecode("v_sum_business");
        List<DicColumnDto> dicColumnDtos = new ArrayList<DicColumnDto>();
        for (DicColumn dicColumn : dicColumns) {
            if (dicColumn.getColumnname().equals("业务名称") || dicColumn.getColumnname().equals("访问量")) {
                DicColumnDto dicColumnDto = new DicColumnDto("", dicColumn);
                dicColumnDtos.add(dicColumnDto);
            }
        }

        // 根据虚拟表字段组装查询
        List<Map> countList = dicTableService.findData(T_BUSINESS_PAGECOUNT, dicColumnDtos, sql.toString(), Integer
                .parseInt(start), Integer.parseInt(limit));

        return countList;
    }

    /**
     * 格式：[{"businessname":"KLOK"},{"sid":"11111"}]
     * @return
     * @throws Exception
     */
    public String saveAccessLog() throws Exception {
       
        String success = "失败";
        String json = request.getParameter("datamessage");
        if (!"".equals(json) && json != null) {
            JSONArray jsonArray = JSONArray.fromObject(json);
            Map<String, String> inputMap = new HashMap<String, String>();
            int len = jsonArray.size();
            if (jsonArray.size() > 0) {
                for (int i = 0; i < len; i++) {
                    JSONObject data = jsonArray.getJSONObject(i);
                    for (Iterator iter = data.keys(); iter.hasNext();) {
                        String key = (String) iter.next();   
                        String value = URLDecoder.decode(data.getString(key),"UTF-8");
                        String value_id="";
                        if("businessname".equalsIgnoreCase(key)){
                            value=value.toLowerCase();
                           
                            String sql="select businesscode,businessname,id,iscount  from  "+T_BUSSINESS_CODE+"  where businesscode='"+value+"'";
                            List<DicColumn> dicColumns = dicTableService.findDBDicColumnsByTablecode(T_BUSSINESS_CODE);
                            List<DicColumnDto> dicColumnDtos = new ArrayList<DicColumnDto>();
                            for (DicColumn dicColumn : dicColumns) {
                                DicColumnDto dicColumnDto = new DicColumnDto("", dicColumn);
                                dicColumnDtos.add(dicColumnDto);
                            }
                            List<Map> codeList = dicTableService.findData(T_BUSINESS_PAGECOUNT, dicColumnDtos, sql,0 , 0);
                           
                            if(codeList!=null){
                                if(!codeList.isEmpty()){
                                     value_id=(String)codeList.get(0).get("id");
                                     value=value_id;
                                }
                            }else{
                                throw new Exception("添加失败");
                            }
                        }
                        
                        inputMap.put(key, value);
                    }

                }
                inputMap.put("createtime", DateUtil.getNowTime("yyyy-MM-dd HH:mm:ss"));
                Map dataMap = dicTableService.saveData(T_BUSINESS_PAGECOUNT, inputMap);
                if (!dataMap.isEmpty()) {
                    success = "成功";
                }

            }

        }

        Map message = new HashMap();
        message.put("msg", success);
        write(JSONObject.fromObject(message).toString());
        return null;
    }
    
    
    
    
    public String buscount() throws BusinessException{
        List<Map> mapList = ViewAction.getDataMap(request);
        List<Map>  maps=new  ArrayList<Map>();
        Map<String, String> result = new HashMap<String, String>();
        for(Map inputMap:mapList){
        Map  returnMap = dicTableService.getDataByKey(T_BUSSINESS_CODE,inputMap);
        returnMap.put("iscount", IS_COUNT_YES); 
        maps.add(returnMap);
        }
        BusinessDealFlowContext context = new BusinessDealFlowContext(
                T_BUSSINESS_CODE, ActionType.ACTIONTYPE_EDIT,maps);
        businessDealFlowEngineService.run(context);
        CacheUtil.clearCacheByTablecode(T_BUSINESS_PAGECOUNT);
        result.put("success", "true");
        result.put("msg", "设置业务统计成功");
        write(JSONObject.fromObject(result).toString());
        return null;
    }
    
    public String unbusCount() throws BusinessException{
        List<Map> mapList = ViewAction.getDataMap(request);
        List<Map>  maps=new  ArrayList<Map>();
        Map<String, String> result = new HashMap<String, String>();
        for(Map inputMap:mapList){
        Map  returnMap = dicTableService.getDataByKey(T_BUSSINESS_CODE,inputMap);
        returnMap.put("iscount", IS_COUNT_NO); 
        maps.add(returnMap);
        }
        BusinessDealFlowContext context = new BusinessDealFlowContext(
                T_BUSSINESS_CODE, ActionType.ACTIONTYPE_EDIT,maps);
        businessDealFlowEngineService.run(context);
        CacheUtil.clearCacheByTablecode(T_BUSINESS_PAGECOUNT);
        result.put("success", "true");
        result.put("msg", "取消业务统计成功");
        write(JSONObject.fromObject(result).toString());
        return null;
    }

    
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(URLEncoder.encode("首页","UTF-8"));
    }
}
